/* global React */
// Results entry — the data-entry surface. Per-driver row: qual, sprint & feature finish,
// pole & fastest-lap toggles; live points preview using the league scoring table.
function ResultsScreen() {
  const { Input, Select, Button, Card, Badge, Avatar, PositionBadge } = window.GT7LeagueDesignSystem_258437;
  const D = window.GT7DATA;
  const SPRINT = { 1: 30, 2: 22, 3: 18, 4: 14, 5: 12, 6: 10 };
  const FEATURE = { 1: 50, 2: 36, 3: 30, 4: 24, 5: 20, 6: 16 };
  const posOpts = ['1', '2', '3', '4', '5', '6', 'DNF'];

  const [rows, setRows] = React.useState(D.drivers.map((d, i) => ({
    number: d.number, name: d.name, color: d.color,
    qual: '', sprint: String(((i) % 6) + 1), feature: String(((i) % 6) + 1),
    pole: i === 0, sprintFL: i === 2, featFL: i === 1,
  })));

  const update = (i, key, val) => setRows(r => r.map((row, j) => j === i ? { ...row, [key]: val } : row));
  // pole / sprintFL / featFL are each awarded to exactly one driver
  const toggle = (i, key) => setRows(r => r.map((row, j) => (
    j === i ? { ...row, [key]: !row[key] } : { ...row, [key]: false }
  )));

  const pts = (row) => {
    const s = SPRINT[row.sprint] || 0;
    const f = FEATURE[row.feature] || 0;
    return s + f + (row.pole ? 10 : 0) + (row.sprintFL ? 5 : 0) + (row.featFL ? 5 : 0);
  };

  const nextRound = D.schedule.find(r => r.status === 'next') || D.schedule[D.schedule.length - 1];

  return (
    <div>
      <PageTitle eyebrow={`Round ${nextRound.round} · ${nextRound.track}`} title="Enter Results"
        note="Fill each driver's finishing positions. Points calculate live from the league table." />

      <Card padded={false} style={{ overflow: 'hidden' }}>
        {/* header */}
        <div style={{
          display: 'grid', gridTemplateColumns: '140px 116px 82px 82px 74px 82px 82px 58px', gap: 12,
          padding: '12px 18px', borderBottom: '1px solid var(--border-strong)', alignItems: 'center',
          fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '.11em', textTransform: 'uppercase', color: 'var(--text-faint)',
        }}>
          <span>Driver</span><span>Qual time</span><span>Sprint</span><span>Feature</span><span>Pole</span><span>Sprint FL</span><span>Feat. FL</span><span style={{ textAlign: 'right' }}>Pts</span>
        </div>

        {rows.map((row, i) => (
          <div key={row.number} style={{
            display: 'grid', gridTemplateColumns: '140px 116px 82px 82px 74px 82px 82px 58px', gap: 12,
            padding: '10px 18px', borderBottom: '1px solid var(--divider)', alignItems: 'center',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Avatar number={row.number} name={row.name} size={30} color={row.color} />
              <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{row.name.split(' ')[0]}</span>
            </div>
            <Input mono placeholder="1:29.4" value={row.qual} onChange={e => update(i, 'qual', e.target.value)} />
            <Select options={posOpts} value={row.sprint} onChange={e => update(i, 'sprint', e.target.value)} />
            <Select options={posOpts} value={row.feature} onChange={e => update(i, 'feature', e.target.value)} />
            <Toggle on={row.pole} color="var(--pole)" onClick={() => toggle(i, 'pole')} />
            <Toggle on={row.sprintFL} color="var(--fastest-lap)" onClick={() => toggle(i, 'sprintFL')} />
            <Toggle on={row.featFL} color="var(--fastest-lap)" onClick={() => toggle(i, 'featFL')} />
            <span style={{ textAlign: 'right', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--text-strong)', fontVariantNumeric: 'tabular-nums' }}>{pts(row)}</span>
          </div>
        ))}
      </Card>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 18 }}>
        <span style={{ fontSize: 13, color: 'var(--text-faint)' }}>Pole +10 · Fastest lap +5 sprint / +5 feature · 100 pts per round</span>
        <div style={{ display: 'flex', gap: 10 }}>
          <Button variant="ghost">Save draft</Button>
          <Button variant="primary">Publish round</Button>
        </div>
      </div>
    </div>
  );
}

function Toggle({ on, color, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 38, height: 24, borderRadius: 999, border: 'none', cursor: 'pointer', padding: 3,
      background: on ? color : 'var(--ink-700)',
      display: 'flex', justifyContent: on ? 'flex-end' : 'flex-start',
      transition: 'background 140ms, justify-content 140ms',
    }}>
      <span style={{ width: 18, height: 18, borderRadius: 999, background: '#0a0d12', boxShadow: '0 1px 2px rgba(0,0,0,.5)' }} />
    </button>
  );
}
window.ResultsScreen = ResultsScreen;
